<template>
  <div class="app-container">
    <!-- 课程信息表单 TODO -->
    <!-- 课程信息表单 -->
    <el-form label-width="120px">

      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
      </el-form-item>

      <!-- 课程讲师 TODO -->
      <el-form-item label="课程讲师">
        <el-select
          v-model="courseInfo.teacherId"
          placeholder="请选择讲师">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"/>
        </el-select>
      </el-form-item>
      <!-- 所属分类 TODO -->
      <el-form-item label="课程分类">
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="请选择课程分类"
          @change="selectChange">
          <el-option
            v-for="subject in subjectList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>
        <el-select
          v-model="courseInfo.subjectId"
          :disabled = "showSubList"
          placeholder="请选择课程子分类">
          <el-option
            v-for="subject in subjectLevelTwoList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>
      </el-form-item>

      <!-- <el-form-item>
        <el-cascader :options="subjectList" :props="{label:'title',value:'id'}"/>
      </el-form-item> -->

      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
      </el-form-item>

      <!-- 课程简介 TODO -->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description"/>
      </el-form-item>

      <!-- 课程封面 TODO -->
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleCoverSuccess"
          :before-upload="beforeCoverUpload"
          :on-error="handleCoverError"
          :action="BASE_API+'/admin/oss/file/upload?module=cover'"
          class="cover-uploader">
          <img v-if="courseInfo.cover" :src="courseInfo.cover">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/> 元
      </el-form-item>
    </el-form>
    <div style="text-align: center">
      <el-button
        :disabled="saveBtnDisabled"
        type="primary"
        @click="saveAndNext()"
      >保存并下一步</el-button
      >
    </div>
  </div>
</template>

<script>
import courseApi from '@/api/course'
import teacherApi from '@/api/teacher'
import subjectApi from '@/api/subject'
// 富文本编辑器
import Tinymce from '@/components/Tinymce'
export default {
  components: { Tinymce },
  data() {
    return {
      saveBtnDisabled: false, // 按钮是否禁用
      courseInfo: {// 表单数据
        courseId: '',
        price: 0,
        lessonNum: 0,
        // 以下解决表单数据不全时insert语句非空校验
        teacherId: '',
        subjectId: '',
        subjectParentId: '',
        cover: '',
        description: ''
      },
      showSubList: true,
      teacherList: [],
      subjectList: [], // 一级分类列表
      subjectLevelTwoList: [], // 二级分类列表
      BASE_API: process.env.BASE_API
    }
  },
  created() {
    // courseId 来源于路由
    // if (this.$route.name === 'CourseInfoEdit') {
    //   this.$parent.courseId = this.$route.params.id
    // }
    // courseId 来源于
    if (this.$parent.courseId) { // 回显
      this.showCourseInfo(this.$parent.courseId)
    } else { // 新增：只渲染一级列表
      this.initTeacherList()
      this.initSubjectList()
    }
  },

  methods: {

    initSubjectList() {
      subjectApi.getNestedTreeList().then(({ data }) => {
        this.subjectList = data.items
      })
    },
    initSubjectTwoList() {
      subjectApi.getNestedTreeList().then(({ data }) => {
        this.subjectList = data.items
        this.subjectList.forEach((item) => {
          if (item.id === this.courseInfo.subjectParentId) {
            this.subjectLevelTwoList = item.children
          }
        })
      })
    },
    initTeacherList() {
      teacherApi.list().then(({ data }) => {
        this.teacherList = data.items
      })
    },
    // 保存并下一步
    saveAndNext() {
      this.saveBtnDisabled = true
      if (!this.$parent.courseId) {
        this.saveCourse()
      } else {
        this.updateCourse()
      }
      this.$parent.active = 1
    },
    saveCourse() {
      courseApi.saveCourseInfo(this.courseInfo).then(({ data, message }) => {
        this.$message.success(message)
        this.$parent.courseId = data.courseId
      })
    },
    updateCourse() {
      courseApi.updateCourseInfoById(this.courseInfo).then(({ message }) => {
        this.$message.success(message)
      })
    },
    selectChange(value) {
      console.log(value)
      this.subjectList.forEach((item) => {
        this.showSubList = false
        if (item.id === value) {
          this.courseInfo.subjectId = ''
          this.subjectLevelTwoList = item.children
        }
      })
    },
    beforeCoverUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleCoverSuccess(response) {
      if (response.success) {
        this.courseInfo.cover = response.data.url
      } else {
        this.$message.error('上传失败!(非http失败)')
      }
      // 强制重新渲染
      // this.$forceUpdate()
    },
    handleCoverError(response) {
      this.$message.error('上传失败!(http失败)')
    },
    showCourseInfo(id) {
      courseApi.getCourseInfo(id).then(({ data }) => {
        this.courseInfo = data.item
        this.showSubList = false
        this.initSubjectTwoList()
      })
    }
  }
}
</script>
<style>
.tinymce-container {
  position: relative;
  line-height: normal;
}
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader .el-upload:hover {
  border-color: #409EFF;
}
.cover-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 640px;
  height: 357px;
  line-height: 357px;
  text-align: center;
}
.cover-uploader img {
  width: 640px;
  height: 357px;
  display: block;
}
</style>
